package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.pojo.AdUser;
import com.heima.admin.service.AdUserService;
import com.heima.common.dtos.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.common.util.JwtUtils;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.AdUserLoginDTO;
import com.heima.model.admin.dtos.LoginResponseDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 管理员用户信息表 服务实现类
 * </p>
 *
 * @author HM
 * @since 2023-03-22
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {


    @Autowired
    private BCryptPasswordEncoder encoder;

    /**
     * 管理平台用户登录
     *
     * @param userLoginDto
     * @return
     */
    @Override
    public ResponseResult<LoginResponseDTO<AdUserDto>> login(AdUserLoginDTO userLoginDto) {
        //  构造查询条件
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, userLoginDto.getName());
        //  查询
        AdUser adUser = this.getOne(queryWrapper);
        if (adUser == null) {
            // 如果根据用户名查询不到用户，报错
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST.getCode(), "用户不存在");
        }
        // 使用BCryptPasswordEncoder提供的方法，比对密码
        boolean b = encoder.matches(userLoginDto.getPassword(), adUser.getPassword());
        if (!b) {
            // 如果密码不匹配，报错
            throw new LeadException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        // 设置token和用户信息返回
        LoginResponseDTO<AdUserDto> loginResponseDTO = new LoginResponseDTO<>();
        String token = JwtUtils.generateTokenExpireInSeconds(adUser.getId(), 3600);
        loginResponseDTO.setToken(token);
        AdUserDto adUserDto = BeanHelper.copyProperties(adUser, AdUserDto.class);
        loginResponseDTO.setUser(adUserDto);

        return ResponseResult.ok(loginResponseDTO);
    }

    @Override
    public String getPassword(String password) {

        return encoder.encode(password);
    }
}
